import { routerRedux } from 'dva/router';
import { accountLogin, logout } from '../services/api';
import { setRole, setAuthority, setAccount, setUser } from '../utils/authority';
import token from '../utils/token';
import { reloadAuthorized } from '../utils/Authorized';
import { message,} from 'antd';
export default {
  namespace: 'login',

  state: {
    status: undefined,
  },

  effects: {
    *login({ payload }, { call, put }) {
      let response = yield call(accountLogin, payload);
      if (response) {
        response.status = 'error';

        if (response && response.code == 200) {
          token.save(response.data.token);
          response.status = 'ok';
        } else if (response.message == undefined) {
          response.message = '服务器出错，请联系管理员';
        }

        yield put({
          type: 'changeLoginStatus',
          payload: response,
        });

        // Login successfully
        if (response.code == 200) {
          reloadAuthorized();

          yield put(routerRedux.push('/'));
        }
        if(!response.success){
            message.error(response.message)
            
        }

      } else {
        response = { status: 'error', message: '服务器出错，请联系管理员' };
        yield put({
          type: 'changeLoginStatus',
          payload: response,
        });
      }

    },

    *logout(_, { call, put, select }) {
      try {
        const urlParams = new URL(window.location.href);
        const pathname = yield select(state => state.routing.location.pathname);
        if (pathname.indexOf('/user/login') < 0) {
          urlParams.searchParams.set('redirect', pathname);
          window.history.replaceState(null, 'login', urlParams.href)
        }
      } finally {
        const response = yield call(logout);
        yield token.remove();
        yield put({
          type: 'changeLoginStatus',
          payload: {
            status: false,
            currRole: '',
            currAuth: '',
            currentMerchantAccount: '',
            currentUser: '',
          },
        });
        reloadAuthorized();
        yield put(routerRedux.push('/user/login'));
      }
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.data && payload.data.currAuth? payload.data.currAuth:null);
      setUser(payload.data);
      // setRole(payload.currAuth);

      return {
        ...state,
        status: payload.status,
        type: payload.type,
        message: payload.message,
      };
    },
  },
};
